/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConfigDateBox.java
 *
 * Created on 2-jan-2011, 15:38:02
 */
package nl.lemval.nododue.dialog;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import javax.swing.JOptionPane;
import nl.lemval.nododue.NodoDueManager;
import nl.lemval.nododue.cmd.CommandInfo;
import nl.lemval.nododue.cmd.CommandInfo.Name;
import nl.lemval.nododue.cmd.CommandLoader;
import nl.lemval.nododue.cmd.NodoCommand;
import nl.lemval.nododue.util.NodoSetting;
import nl.lemval.nododue.util.NodoSettingRetriever;
import nl.lemval.nododue.util.SerialCommunicator;
import org.freixas.jcalendar.JCalendarCombo;
import org.jdesktop.application.Action;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;

/**
 *
 * @author Michael
 */
public class ConfigDateBox extends javax.swing.JDialog {

    private JCalendarCombo datePicker;
    private JCalendarCombo timePicker;

    /** Creates new form ConfigDateBox */
    public ConfigDateBox(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initCalendar();
        
        DialogUtil.configureCloseOnEscape(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        actionGroup = new javax.swing.ButtonGroup();
        selectionPanel = new javax.swing.JPanel();
        readTimeButton = new javax.swing.JRadioButton();
        syncButton = new javax.swing.JRadioButton();
        writeTimeButton = new javax.swing.JRadioButton();
        calendarPanel = new javax.swing.JPanel();
        contentPanel = new javax.swing.JPanel();
        actionPanel = new javax.swing.JPanel();
        activateButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(nl.lemval.nododue.NodoDueManager.class).getContext().getResourceMap(ConfigDateBox.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N
        setResizable(false);

        selectionPanel.setName("selectionPanel"); // NOI18N

        actionGroup.add(readTimeButton);
        readTimeButton.setSelected(true);
        readTimeButton.setText(resourceMap.getString("readTimeButton.text")); // NOI18N
        readTimeButton.setName("readTimeButton"); // NOI18N

        actionGroup.add(syncButton);
        syncButton.setText(resourceMap.getString("syncButton.text")); // NOI18N
        syncButton.setName("syncButton"); // NOI18N

        actionGroup.add(writeTimeButton);
        writeTimeButton.setText(resourceMap.getString("writeTimeButton.text")); // NOI18N
        writeTimeButton.setName("writeTimeButton"); // NOI18N

        javax.swing.GroupLayout selectionPanelLayout = new javax.swing.GroupLayout(selectionPanel);
        selectionPanel.setLayout(selectionPanelLayout);
        selectionPanelLayout.setHorizontalGroup(
            selectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(selectionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(selectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(readTimeButton)
                    .addComponent(syncButton)
                    .addComponent(writeTimeButton))
                .addContainerGap(81, Short.MAX_VALUE))
        );
        selectionPanelLayout.setVerticalGroup(
            selectionPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(selectionPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(readTimeButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(syncButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(writeTimeButton)
                .addContainerGap(72, Short.MAX_VALUE))
        );

        getContentPane().add(selectionPanel, java.awt.BorderLayout.CENTER);

        calendarPanel.setName("calendarPanel"); // NOI18N
        calendarPanel.setPreferredSize(new java.awt.Dimension(400, 65));

        contentPanel.setName("contentPanel"); // NOI18N
        contentPanel.setPreferredSize(new java.awt.Dimension(376, 45));

        javax.swing.GroupLayout contentPanelLayout = new javax.swing.GroupLayout(contentPanel);
        contentPanel.setLayout(contentPanelLayout);
        contentPanelLayout.setHorizontalGroup(
            contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 376, Short.MAX_VALUE)
        );
        contentPanelLayout.setVerticalGroup(
            contentPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 52, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout calendarPanelLayout = new javax.swing.GroupLayout(calendarPanel);
        calendarPanel.setLayout(calendarPanelLayout);
        calendarPanelLayout.setHorizontalGroup(
            calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
            .addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(calendarPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        calendarPanelLayout.setVerticalGroup(
            calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 65, Short.MAX_VALUE)
            .addGroup(calendarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(calendarPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)))
        );

        getContentPane().add(calendarPanel, java.awt.BorderLayout.PAGE_START);

        actionPanel.setName("actionPanel"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(nl.lemval.nododue.NodoDueManager.class).getContext().getActionMap(ConfigDateBox.class, this);
        activateButton.setAction(actionMap.get("performOperation")); // NOI18N
        activateButton.setText(resourceMap.getString("activateButton.text")); // NOI18N
        activateButton.setName("activateButton"); // NOI18N
        actionPanel.add(activateButton);

        getContentPane().add(actionPanel, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    @Action
    public void performOperation() {
        Calendar cal = Calendar.getInstance();

        if (syncButton.isSelected()) {
            sendDateTime(cal);
        } else if (writeTimeButton.isSelected()) {
            cal.setTime(datePicker.getDate());
            Calendar time = Calendar.getInstance();
            time.setTime(timePicker.getDate());
            cal.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
            cal.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
            cal.set(Calendar.SECOND, time.get(Calendar.SECOND));
            sendDateTime(cal);
        } else if (readTimeButton.isSelected()) {
            cal = retrieveDateTime();
            if (cal != null) {
                datePicker.setDate(cal.getTime());
                timePicker.setDate(cal.getTime());
                datePicker.invalidate();
                timePicker.invalidate();
            }
        }
    }

    private void initCalendar() {
        Calendar calendar = Calendar.getInstance();
        datePicker =
                new JCalendarCombo(
                calendar,
                Locale.getDefault(),
                JCalendarCombo.DISPLAY_DATE,
                true);
        datePicker.setMinimumSize(new Dimension(250, 23));
        datePicker.setPreferredSize(new Dimension(250, 23));

        timePicker =
                new JCalendarCombo(
                calendar,
                Locale.getDefault(),
                JCalendarCombo.DISPLAY_TIME,
                true);
        datePicker.setMinimumSize(new Dimension(250, 23));
        timePicker.setPreferredSize(new Dimension(250, 23));

        contentPanel.setLayout(new GridLayout(2, 1));
        contentPanel.add(datePicker);
        contentPanel.add(timePicker);
    }

    public void sendDateTime(Calendar cal) {
        if (NodoDueManager.hasConnection() == false) {
            return;
        }
        String day = String.valueOf(cal.get(Calendar.DATE));
        String mon = String.valueOf(cal.get(Calendar.MONTH) + 1);
        String era = String.valueOf(cal.get(Calendar.YEAR) / 100);
        String year = String.valueOf(cal.get(Calendar.YEAR) % 100);
        String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(cal.get(Calendar.MINUTE));
        String dayOfWeek = String.valueOf(cal.get(Calendar.DAY_OF_WEEK));

        SerialCommunicator comm =
                NodoDueManager.getApplication().getSerialCommunicator();
        try {
            comm.send(new NodoCommand(CommandLoader.get(Name.ClockSetDOW), dayOfWeek, ""));
            comm.send(new NodoCommand(CommandLoader.get(Name.ClockSetDate), day, mon));
            comm.send(new NodoCommand(CommandLoader.get(Name.ClockSetYear), era, year));
            comm.send(new NodoCommand(CommandLoader.get(Name.ClockSetTime), hour, mins));
            comm.waitCommand(500);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, MessageFormat.format(getResource("rtc.updatefailed"), e.getMessage()));
        }
    }

    private Calendar retrieveDateTime() {
        if (NodoDueManager.hasConnection() == false) {
            return null;
        }
        Collection<CommandInfo> cis = new HashSet<CommandInfo>();

        cis.add(CommandLoader.get(Name.ClockSetDate));
        cis.add(CommandLoader.get(Name.ClockSetYear));
        cis.add(CommandLoader.get(Name.ClockSetTime));
        cis.add(CommandLoader.get(Name.ClockSetDOW));

        // TODO: Allow to send to another unit.
        Collection<NodoSetting> settings = NodoSettingRetriever.getSettings(cis, 0);
        if (settings == null) {
            return null;
        }

        Calendar cal = Calendar.getInstance();
        int total = 0;
        for (NodoSetting nodoSetting : settings) {
            Name name = Name.valueOf(nodoSetting.getName());

            int value1, value2 = 0;
            if ( name == Name.ClockSetDOW ) {
                value1 = Integer.parseInt(nodoSetting.getAttributeData1());
            } else {
                value1 = Integer.parseInt(nodoSetting.getAttributeValue1());
                value2 = Integer.parseInt(nodoSetting.getAttributeValue2());
            }
            total = total + value1 + value2;

            switch (name) {
                case ClockSetDate:
                    cal.set(Calendar.DAY_OF_MONTH, value1);
                    cal.set(Calendar.MONTH, value2 - 1);
                    break;
                case ClockSetYear:
                    cal.set(Calendar.YEAR, value1 * 100 + value2);
                    break;
                case ClockSetTime:
                    cal.set(Calendar.HOUR_OF_DAY, value1);
                    cal.set(Calendar.MINUTE, value2);
                    break;
                case ClockSetDOW:
                    cal.set(Calendar.DAY_OF_WEEK, value1);
                    break;
            }
        }
        if (total == 0 || total == 20) {
            JOptionPane.showMessageDialog(this, getResource("rtc.notavailable"));
            return null;
        }
        return cal;
    }
    
    private String getResource(String resource) {
        ResourceMap resourceMap = Application.getInstance(NodoDueManager.class).getContext().getResourceMap(getClass());
        return resourceMap.getString(resource);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup actionGroup;
    private javax.swing.JPanel actionPanel;
    private javax.swing.JButton activateButton;
    private javax.swing.JPanel calendarPanel;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JRadioButton readTimeButton;
    private javax.swing.JPanel selectionPanel;
    private javax.swing.JRadioButton syncButton;
    private javax.swing.JRadioButton writeTimeButton;
    // End of variables declaration//GEN-END:variables
}
